<?php
/*****************************************************************************\
+-----------------------------------------------------------------------------+
| X-Cart                                                                      |
| Copyright (c) 2001-2007 Ruslan R. Fazliev <rrf@rrf.ru>                      |
| All rights reserved.                                                        |
+-----------------------------------------------------------------------------+
| PLEASE READ  THE FULL TEXT OF SOFTWARE LICENSE AGREEMENT IN THE "COPYRIGHT" |
| FILE PROVIDED WITH THIS DISTRIBUTION. THE AGREEMENT TEXT IS ALSO AVAILABLE  |
| AT THE FOLLOWING URL: http://www.x-cart.com/license.php                     |
|                                                                             |
| THIS  AGREEMENT  EXPRESSES  THE  TERMS  AND CONDITIONS ON WHICH YOU MAY USE |
| THIS SOFTWARE   PROGRAM   AND  ASSOCIATED  DOCUMENTATION   THAT  RUSLAN  R. |
| FAZLIEV (hereinafter  referred to as "THE AUTHOR") IS FURNISHING  OR MAKING |
| AVAILABLE TO YOU WITH  THIS  AGREEMENT  (COLLECTIVELY,  THE  "SOFTWARE").   |
| PLEASE   REVIEW   THE  TERMS  AND   CONDITIONS  OF  THIS  LICENSE AGREEMENT |
| CAREFULLY   BEFORE   INSTALLING   OR  USING  THE  SOFTWARE.  BY INSTALLING, |
| COPYING   OR   OTHERWISE   USING   THE   SOFTWARE,  YOU  AND  YOUR  COMPANY |
| (COLLECTIVELY,  "YOU")  ARE  ACCEPTING  AND AGREEING  TO  THE TERMS OF THIS |
| LICENSE   AGREEMENT.   IF  YOU    ARE  NOT  WILLING   TO  BE  BOUND BY THIS |
| AGREEMENT, DO  NOT INSTALL OR USE THE SOFTWARE.  VARIOUS   COPYRIGHTS   AND |
| OTHER   INTELLECTUAL   PROPERTY   RIGHTS    PROTECT   THE   SOFTWARE.  THIS |
| AGREEMENT IS A LICENSE AGREEMENT THAT GIVES  YOU  LIMITED  RIGHTS   TO  USE |
| THE  SOFTWARE   AND  NOT  AN  AGREEMENT  FOR SALE OR FOR  TRANSFER OF TITLE.|
| THE AUTHOR RETAINS ALL RIGHTS NOT EXPRESSLY GRANTED BY THIS AGREEMENT.      |
|                                                                             |
| The Initial Developer of the Original Code is Ruslan R. Fazliev             |
| Portions created by Ruslan R. Fazliev are Copyright (C) 2001-2007           |
| Ruslan R. Fazliev. All Rights Reserved.                                     |
+-----------------------------------------------------------------------------+
\*****************************************************************************/

#
# $Id: cc_protxdir.php,v 1.28.2.19 2007/09/05 11:53:58 zaa Exp $
#

if (!isset($REQUEST_METHOD)) {
    $REQUEST_METHOD = $HTTP_SERVER_VARS["REQUEST_METHOD"];
}
if ($REQUEST_METHOD == "POST" && !empty($HTTP_POST_VARS['PaRes']) && !empty($HTTP_POST_VARS['MD'])) {
	require "./auth.php";
	$md = $HTTP_POST_VARS['MD'];
	$post = array();
	$post[] = "MD=".$md;
	$post[] = "PARes=".$HTTP_POST_VARS['PaRes'];
	$bill_output["sessid"] = func_query_first_cell("SELECT sessionid FROM $sql_tbl[cc_pp3_data] WHERE ref='".$HTTP_POST_VARS['MD']."'");
	$secure_verified_3d = true;
	x_session_register("module_params");
}
if (!defined('XCART_START')) { header("Location: ../"); die("Access denied"); }

x_load('http');

$pp_merch = $module_params["param01"];
$pp_curr = $module_params["param03"];

# Determine request URL (simulator, test server or live server)
switch ($module_params['testmode']) {
case 'S':
	$pp_test = 'https://ukvpstest.protx.com:443/VSPSimulator/VSPDirectGateway.asp';
	break;
case 'Y':
	$pp_test = 'https://ukvpstest.protx.com:443/vspgateway/service/vspdirect-register.vsp';
	break;
default:
	$pp_test = 'https://ukvps.protx.com:443/vspgateway/service/vspdirect-register.vsp';
}

x_session_register("already_posted");
if ($secure_verified_3d && !$already_posted) {
	# Determine 3-D Secure callback URL (simulator, test server or live server)
	switch ($module_params['testmode']) {
	case 'S':
		$pp_test = 'https://ukvpstest.protx.com:443/VSPSimulator/VSPDirectCallback.asp';
		break;
	case 'Y':
		$pp_test = 'https://ukvpstest.protx.com:443/vspgateway/service/direct3dcallback.vsp';
		break;
	default:
		$pp_test = 'https://ukvps.protx.com:443/vspgateway/service/direct3dcallback.vsp';
	}
	list($a, $return) = func_https_request("POST", $pp_test, $post);
	$already_posted = true;
} else {	
	
	$already_posted = false;
	$pp_shift = $module_params["param05"];
	$_orderids = join("-",$secure_oid);

	if (is_visa($userinfo["card_number"])) {
		if ($userinfo["card_type"] != 'UKE')
			$userinfo["card_type"] = "VISA";
	} elseif (is_switch($userinfo["card_number"]))
		$userinfo["card_type"] = "SWITCH";
	elseif (is_amex($userinfo["card_number"]))
		$userinfo["card_type"] = "AMEX";
	elseif (is_mc($userinfo["card_number"]))
		$userinfo["card_type"] = "MC";
	elseif (is_solo($userinfo["card_number"]))
		$userinfo["card_type"] = "SOLO";
	elseif (is_delta($userinfo["card_number"]))
		$userinfo["card_type"] = "DELTA";
	elseif (is_dc($userinfo["card_number"]))
		$userinfo["card_type"] = "DINERS";
	elseif (is_jcb($userinfo["card_number"]))
		$userinfo["card_type"] = "JCB";
	elseif (!defined("INNER_PAYMENT")) {
		$top_message = array(
			"content" => func_get_langvar_by_name("txt_protxdir_wrong_cc_type"),
			"type" => "E",
			"anchor" => "ccinfo"
		);
		func_header_location($xcart_catalogs['customer']."/cart.php?mode=checkout&err=fields&paymentid=".$paymentid);

	} else {
		$bill_output = array(
			"code" => 2,
			"billmes" => "Declined: ".func_get_langvar_by_name("txt_protxdir_wrong_cc_type")
		);
		return;
	}

	$post = array();
	$post[] = "VPSProtocol=2.22";
	$post[] = "TxType=PAYMENT";
	$post[] = "Vendor=".$pp_merch;
	$post[] = "VendorTxCode=".$pp_shift.$_orderids;
	$post[] = "Amount=".$cart["total_cost"];
	$post[] = "Currency=".$pp_curr;
	$post[] = "Description=Your Cart";
	$post[] = "CardHolder=".$userinfo["card_name"];
	$post[] = "CardNumber=".$userinfo["card_number"];
	$post[] = "ExpiryDate=".$userinfo["card_expire"];
	$post[] = "CV2=".$userinfo["card_cvv2"];
	$post[] = "CardType=".$userinfo["card_type"];

	$billing_address = array();
	$billing_address[] = $userinfo["b_address"];
	if (!empty($userinfo["b_address_2"]))
		$billing_address[] = $userinfo["b_address_2"];
	$billing_address[] = $userinfo["b_city"];
	if (!empty($userinfo["b_countyname"]))
		$billing_address[] = $userinfo["b_countyname"];
	$billing_address[] = empty($userinfo["b_statename"]) ? $userinfo["b_state"] : $userinfo["b_statename"];
	$billing_address[] = empty($userinfo["b_countryname"]) ? $userinfo["b_country"] : $userinfo["b_countryname"];

	$post[] = "BillingAddress=".substr(implode(" ", $billing_address), 0, 200);
	$post[] = "BillingPostCode=".substr($userinfo["b_zipcode"], 0, 10);

	$ship_address = array();
	$ship_address[] = $userinfo["s_address"];
	if (!empty($userinfo["s_address_2"]))
	$ship_address[] = $userinfo["s_address_2"];
	$ship_address[] = $userinfo["s_city"];
	if (!empty($userinfo["s_countyname"]))
		$ship_address[] = $userinfo["s_countyname"];
	$ship_address[] = empty($userinfo["s_statename"]) ? $userinfo["s_state"] : $userinfo["s_statename"];
	$ship_address[] = empty($userinfo["s_countryname"]) ? $userinfo["s_country"] : $userinfo["s_countryname"];

	if (!empty($ship_address) && !empty($userinfo["s_zipcode"])) {
		$post[] = "DeliveryAddress=".substr(implode(" ", $ship_address), 0, 200);
		$post[] = "DeliveryPostCode=".substr($userinfo["s_zipcode"], 0, 10);
	}

	$post[] = "CustomerName=".substr($userinfo["firstname"]." ".$userinfo["lastname"], 0, 100);
	$post[] = "ContactNumber=".substr(str_replace(array(" ","-"), array("",""), $userinfo["phone"]), 0, 20);
	$post[] = "ContactFax=".substr(str_replace(array(" ","-"), array("",""), $userinfo["fax"]), 0, 20);
	$post[] = "CustomerEMail=".substr($userinfo["email"], 0, 255);
	$post[] = "Basket=".func_cc_protx_get_basket();
	$post[] = "GiftAidPayment=0";
	$post[] = "ApplyAVSCV2=".$module_params['param06'];
	$post[] = "Apply3DSecure=".$module_params['param07'];
	$post[] = "ClientIPAddress=".func_get_valid_ip($REMOTE_ADDR);

	if ($userinfo["card_type"] == "SOLO" || $userinfo["card_type"] == 'SWITCH') {
		$userinfo['card_issue_no'] = (empty($userinfo['card_issue_no'])) ? "" : trim($userinfo['card_issue_no']);
		$post[] = "IssueNumber=" . $userinfo['card_issue_no'];
	}
	list($a,$return)=func_https_request("POST",$pp_test,$post);
}
$ret = str_replace("\r\n","&",$return);

$ret_arr = explode("&",$ret);
$response = array();
foreach ($ret_arr as $ret) {
	preg_match("/([^=]+?)=(.+)/", $ret, $matches); 
	$response[$matches[1]] = $matches[2];
}

if (trim($response['Status']) == "3DAUTH") {

	x_session_register("module_params");
	db_query("REPLACE INTO $sql_tbl[cc_pp3_data] (ref,sessionid,trstat) VALUES ('".trim($response['MD'])."','".$XCARTSESSID."','GO|".implode('|',$secure_oid)."')");
?>
<form action="<?php echo $response['ACSURL']; ?>" method="post" id="3d_form">
<input type="hidden" name="PaReq" value="<?php echo $response['PAReq']; ?>"/>
<input type="hidden" name="TermUrl" value="<?php echo $https_location."/payment/cc_protxdir.php"?>"/>
<input type="hidden" name="MD" value="<?php echo $response['MD']; ?>"/>
<NOSCRIPT>
<center><p>Please click button below to Authenticate your card</p><input type="submit" value="Go"/></p></center>
</NOSCRIPT>
</form>
<script language="JavaScript">
	document.getElementById('3d_form').submit();
</script>
<?
die("Redirecting to 3D secure server...");
} elseif (trim($response['Status']) == "OK") {
	$bill_output["code"] = 1;
	$bill_output["billmes"] = "AuthNo: ".$response['TxAuthNo']."; SecurityKey: ".$response['SecurityKey']."\n";
} else {
	$bill_output["code"] = 2;
	$bill_output["billmes"] = "Status: ".$response['StatusDetail']." (".trim($response['Status']).")\n";
}

if (!empty($response['VPSTxId'])) {
	$bill_output["billmes"].= " (TxID: ".trim($response['VPSTxId']).")\n";
}

if (!empty($response['AVSCV2'])) {
	$bill_output["billmes"].= " (AVS/CVV2: {".trim($response['AVSCV2'])."})\n";
}
if (!empty($response['AddressResult'])) {
	$bill_output["billmes"] .= " (Address: {".trim($response['AddressResult'])."})\n";
}
if (!empty($response['PostCodeResult'])) {
	$bill_output["billmes"] .= " (PostCode: {".trim($response['PostCodeResult'])."})\n";
}
if (!empty($response['CV2Result'])) {
	$bill_output["billmes"] .= " (CV2: {".trim($response['CV2Result'])."})\n";
}
if (!empty($response['3DSecureStatus'])) {
	$bill_output["billmes"] .= " (3D Result: {".trim($response['3DSecureStatus'])."})\n";
}
if ($secure_verified_3d) {
	$skey = $md;
	$bill_output["sessid"] = func_query_first_cell("SELECT sessionid FROM $sql_tbl[cc_pp3_data] WHERE ref='".trim($skey)."'");

	require $xcart_dir."/payment/payment_ccend.php";
	exit;
}	
?>
